大家好,最近開始在學 TypeScript,除了官方文件以外,也會翻閱保哥的免費電子書 will 保哥 - TypeScript 新手指南 (TS 影片介紹)
TypeHero 這個網站也是個很棒的學習資源~ 千萬別錯過!!
這篇文章主要會圍繞在 TypeHero 和記錄刷題的心得
會挑選兩題適合新手的題目(新手是我 (〃∀〃)
TypeHero 是由一位 Netflix 的資深工程師所開發的開源專案
你可以把它想成是 TypeScript 版的 Leecode,從簡單到困難的 TypeScript 題目都有!例如以 TypeHero 的「TypeScript Foundations」12 道題目來說,它涵蓋了從基礎語法到進階概念的一系列題目。像是「原始資料型別」、「型別別名」、「字串字面量型別」、「索引簽名」、「typeof」等
只要有 Github 帳號,登入後即可開始刷題!
適合新手
: Tracks > TypeScript Foundations 的 12 道基礎題目適合泛型新手
:Explore > Beginner 想多練習更多初階泛型應用可以試試看 Beginner 裡的 14 道初階泛型題目適合寫過 1 年經驗的 TypeScript 開發者
:Explore > Easy適合中階開發者
:Explore > MediumTypeHero 網址 https://typehero.dev/
GitHub 開源專案 https://github.com/typehero/typehero
TypeScript 的基礎概念之一就是能夠創建「原始型別」
這題需要在程式中添加「原始類型」,直到錯誤消失為止。解題中你會需要為物件添加上消失的屬性
const playSong = (artistName, year) => {
return `${artistName} was released in the year ${year}`;
};
const artistName = 'Frank Zappa';
const age = 52;
interface Musician {
artistName: string;
// add the rest
}
const musicianInfo = ({ artistName, age, deceased }) => {
return `${artistName}, age ${age}${deceased ? ' (deceased)' : ''}`;
};
musicianInfo({
artistName,
age,
deceased: true,
});
// playSong 函式接收兩個參數 artistName, year,型別分別是 string 和 number
const playSong = (artistName: string, year: number) => {
return `${artistName} was released in the year ${year}`;
};
// 這兩個變數在 TypeHero 編輯器裡沒有出現紅色蚯蚓警告,若你一開始忘記定義,送出就會報錯了
const artistName: string = "Frank Zappa";
const age: number = 52;
// 介面的名稱:開頭要大小寫,代表一個型別
interface Musician {
artistName: string;
age: number;
// 這裡官方有提示,下面也可以看到其實 musicianInfo 函式會帶入三個參數,唯獨少了 deceased
// 在 interface 中物件必須跟介面的定義一致,多出或少了介面中的屬性都不行
deceased: boolean;
}
// musicianInfo 接受一個物件作為參數,這個參數必須符合 Musician 的介面結構
const musicianInfo = ({ artistName, age, deceased }: Musician) => {
return `${artistName}, age ${age}${deceased ? " (deceased)" : ""}`;
};
musicianInfo({
artistName,
age,
deceased: true,
});
const musicianInfo = ({ artistName, age, deceased }: Musician) => {...}
題目二是要使用「型別別名(type aliases)」來去定義型別
這題需要創建必要的型別別名,如 Name、Year、Payload 等,請仔細閱讀題目附上的測試內容
// We completed the first alias (`Name`) for you to see as an example
type Name = string;
// Now try replacing `unknown` with a primitive data type that might be appropriate for `Year`
type Year = unknown;
type IsOperational = unknown;
type Payload = {
name: Name;
// the tests show that you need a `mass` property here
// but first you might need to create an alias for `Kilograms`
// because that's the value of `mass`
};
// We completed the first alias (`Name`) for you to see as an example
type Name = string;
type Year = number; // 型別從底下測試可得知
type Count = number; // 從底下測試的 Spacecraft 介面 裡會知道 Count 用於計數,所以型別應是數字
type IsOperational = boolean; // 型別從底下測試可得知
// create an alias for `Kilograms`
type Kilograms = number;
type Payload = {
name: Name;
mass: Kilograms;
// the tests show that you need a `mass` property here
// but first you might need to create an alias for `Kilograms`
// because that's the value of `mass`
};
大部分的型別都可以從底下測試得知,包含 Payload 裡有 mass 屬性也是